import { Box, Button, Checkbox, IconButton, InputAdornment, Table, TableBody, TableContainer, TableFooter, TableHead, TableRow, TextField } from '@mui/material';
import React, { JSX } from 'react';
import { NulHeaderTableCell, NulTableCell } from '../../components/NulHeaderTable';
import { removeElementFromArray } from '../../util/Arrays';
import { ReactComponent as SearchIcon } from '../../assets/search.svg';
import { ReactComponent as CreateIcon } from '../../assets/create.svg';
import ClearIcon from '@mui/icons-material/Clear';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';
import { WarehouseEntry, deleteWarehouse, fetchAllWarehouse, selectWarehouseEntries, selectWarehouseFetched } from '../../actions/WarehouseManagement';
import { useAppDispatch, useAppSelector } from '../../actions/hook';
import { CreateWarehouse } from '../WarehouseDialog/CreateWarehouse';
import { ModifyWarehouse } from '../WarehouseDialog/ModifyWarehouse';
import { fetchAllUserEntries, selectUserEntries, selectUserFetched } from '../../actions/UserManagement';

interface WarehouseManagementProps {

}

function WarehouseManagement(props: WarehouseManagementProps): JSX.Element {

  const [filterValue, setFilterValue] = React.useState<string>('');
  const [openWarehouseDialog, setOpenWarehouseDialog] = React.useState<boolean>(false);
  const [openModifyDialog, setOpenModifyDialog] = React.useState<boolean>(false);

  const [filteredWarehouseEntries, setFilteredWarehouseEntries] = React.useState<WarehouseEntry[]>([]);
  const [checkedIdList, setCheckedIdList] = React.useState<number[]>([]);
  const [modifyEntry, setModifyEntry] = React.useState<WarehouseEntry>({
    id: 0, name: '', type: '', address: '', status: 'open', authority: 0
  });

  const dispatch = useAppDispatch();

  const fetchedWarehousesEntries = useAppSelector(selectWarehouseFetched);
  const warehouseEntries = useAppSelector(selectWarehouseEntries);

  const fetchedUserEntries = useAppSelector(selectUserFetched);
  const userEntries = useAppSelector(selectUserEntries);

  React.useEffect(() => {
    if (!fetchedWarehousesEntries) {
      dispatch(fetchAllWarehouse());
    }
    if (!fetchedUserEntries) {
      dispatch(fetchAllUserEntries());
    }
  });

  React.useEffect(() => {
    if (warehouseEntries !== undefined) {
      setFilteredWarehouseEntries(warehouseEntries.filter(val => val.name.indexOf(filterValue) !== -1));
      setCheckedIdList([]);
    }
  }, [warehouseEntries, filterValue]);

  const handleModify = (row: WarehouseEntry) => {
    setModifyEntry(row);
    setOpenModifyDialog(true);
  };

  const handleDelete = (row: WarehouseEntry) => {
    dispatch(deleteWarehouse({ id: row.id }));
  };

  const headerChecked: boolean = checkedIdList.length !== 0 && checkedIdList.length === filteredWarehouseEntries.length;
  const headerIndeterminate: boolean = checkedIdList.length !== 0 && checkedIdList.length < filteredWarehouseEntries.length;

  return (
    <>
      <Box sx={{ padding: '30px 30px 30px 30px', flex: 'none', flexGrow: 1 }}>
        <Box sx={{
          fontFamily: 'Open Sans',
          fontStyle: 'normal',
          fontWeight: 600,
          fontSize: '22px',
          lineHeight: '125%'
        }}>
          Warehouse Management
        </Box>
        <Box sx={{
          marginTop: '20px', width: '100%', height: '40px', display: 'flex',
          flexDirection: 'row', justifyContent: 'space-between'
        }}>
          <Box sx={{ width: '456px' }}>
            <TextField
              size='small'
              fullWidth={true}
              InputProps={{
                startAdornment: (
                  <InputAdornment position='start' sx={{}}>
                    <SearchIcon />
                  </InputAdornment>
                ),
                endAdornment: (
                  <IconButton edge="end" onClick={() => { setFilterValue(''); }}>
                    <ClearIcon fontSize='small' />
                  </IconButton>
                )
              }}
              placeholder='Search warehouse'
              value={filterValue}
              onChange={(action) => { setFilterValue(action.target.value); }}
              sx={{
                paddingLeft: '0px'
              }}
            />
          </Box>
          <Box sx={{
            flex: 'none',
            order: 1,
            flexGrow: 0
          }}>
            <Button
              variant="contained"
              disableElevation
              startIcon={<CreateIcon />}
              onClick={() => {
                setOpenWarehouseDialog(true);
              }}
              sx={{
                height: '40px',
                textTransform: 'none'
              }}
            >
              Create
            </Button>
          </Box>
        </Box>
        <Box sx={{
          marginTop: '20px',
          width: '100%'
        }}>
          <TableContainer
            sx={{
              width: '100%'
            }}
          >
            <Table
              stickyHeader
              sx={{
                border: '1px solid #DFE4E8',
                borderRadius: '8px',
                fontFamily: 'Open Sans',
                fontStyle: 'normal',
              }}
            >
              <TableHead sx={{ border: '8px 8px 0px 0px' }}>
                <TableRow sx={{
                  height: '42px',
                  padding: 0,
                  width: '100%',
                  display: 'flex',
                  alignItems: 'center',
                }}>
                  <Box sx={{ height: '100%' }}>
                    <NulHeaderTableCell
                      sx={{
                        width: '62px',
                        borderTopLeftRadius: '8px',
                        justifyContent: 'center',
                        flexGrow: 0
                      }}
                    >
                      <Checkbox
                        sx={{
                          width: '42px',
                          display: 'flex',
                          justifyContent: 'center',
                        }}
                        onClick={() => {
                          if (headerChecked) {
                            setCheckedIdList([]);
                          }
                          else {
                            setCheckedIdList(filteredWarehouseEntries.map(entry => entry.id));
                          }
                        }}
                        checked={headerChecked}
                        indeterminate={headerIndeterminate}
                      />
                    </NulHeaderTableCell>
                  </Box>
                  <Box sx={{ display: 'flex', flexDirection: 'row', flexGrow: 1, position: 'relative', height: '100%' }}>
                    <NulHeaderTableCell sx={{ width: '5%' }}>
                      ID
                    </NulHeaderTableCell>
                    <NulHeaderTableCell sx={{ width: '5%' }} />
                    <NulHeaderTableCell sx={{ width: '25%' }}>
                      Name
                    </NulHeaderTableCell>
                    <NulHeaderTableCell sx={{ width: '15%' }}>
                      Type
                    </NulHeaderTableCell>
                    <NulHeaderTableCell sx={{ width: '25%' }}>
                      Address
                    </NulHeaderTableCell>
                    <NulHeaderTableCell sx={{ width: '25%', borderTopRightRadius: '8px' }}>
                      Operations
                    </NulHeaderTableCell>
                  </Box>
                </TableRow>
              </TableHead>
              <TableBody
                sx={{
                  minHeight: '410px', maxHeight: '410px', display: 'block', overflowY: 'auto'
                }}
              >
                {filteredWarehouseEntries.map(row => {
                  const checkedIndex: number = checkedIdList.indexOf(row.id);
                  return (
                    <TableRow
                      key={row.id}
                      sx={{
                        width: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        height: '42px'
                      }}
                    >
                      <Box sx={{ height: '100%' }}>
                        <NulTableCell sx={{ width: '62px', justifyContent: 'center', flexGrow: 0 }}>
                          <Checkbox
                            sx={{
                              width: '42px',
                              display: 'flex',
                              justifyContent: 'center',
                            }}
                            checked={checkedIndex !== -1}
                            onChange={(event, checked) => {
                              if (checked) {
                                if (checkedIndex === -1) {
                                  setCheckedIdList([...checkedIdList, row.id]);
                                }
                              }
                              else {
                                if (checkedIndex !== -1) {
                                  setCheckedIdList(removeElementFromArray(checkedIdList, checkedIndex));
                                }
                              }
                            }}
                          />
                        </NulTableCell>
                      </Box>
                      <Box sx={{ display: 'flex', flexDirection: 'row', flexGrow: 1, position: 'relative', height: '100%' }}>
                        <NulTableCell sx={{ width: '5%' }}>
                          {row.id}
                        </NulTableCell>
                        <NulTableCell sx={{ width: '5%' }}>
                          {/*row.status*/}
                        </NulTableCell>
                        <NulTableCell sx={{ width: '25%' }}>
                          {row.name}
                        </NulTableCell>
                        <NulTableCell sx={{ width: '15%' }}>
                          {row.type}
                        </NulTableCell>
                        <NulTableCell sx={{ width: '25%' }}>
                          {row.address}
                        </NulTableCell>
                        <NulTableCell sx={{ width: '25%', display: 'flex' }}>
                          <IconButton aria-label='edit' onClick={() => { handleModify(row); }}>
                            <EditIcon />
                          </IconButton>
                          <IconButton aria-label='delete' onClick={() => { handleDelete(row); }}>
                            <DeleteIcon />
                          </IconButton>
                        </NulTableCell>
                      </Box>
                    </TableRow>
                  );
                })}
              </TableBody>
              <TableFooter
                sx={{
                  minHeight: '34px',
                  maxHeight: '44px',
                  display: 'block',
                  backgroundColor: '#F1F3F5',
                  borderRadius: '0px 0px 8px 8px',
                }}
              ></TableFooter>
            </Table>
          </TableContainer>
        </Box>
      </Box>
      <CreateWarehouse
        open={openWarehouseDialog}
        onClose={() => { setOpenWarehouseDialog(false); }}
        userEntries={userEntries}
      />
      <ModifyWarehouse
        open={openModifyDialog}
        onClose={() => { setOpenModifyDialog(false); }}
        warehouseEntry={modifyEntry}
        userEntries={userEntries}
      />
    </>
  );
}

export default WarehouseManagement;